package com.v1.video.db.service;

import java.util.List;

import com.v1.video.AppContext;
import com.v1.video.db.dao.CacheTB;
import com.v1.video.db.dao.CacheTBDao;
import com.v1.video.dbcore.greenrobot.dao.query.QueryBuilder;
import com.v1.video.httpmanager.MemoryCache;

public class CacheDB {

	private static CacheDB mInstance;
	private CacheTBDao mCacheTBDao;

	private CacheDB() {
		mCacheTBDao = AppContext.getDaoSession().getCacheTBDao();
	}

	public static CacheDB getInstance() {
		if (mInstance == null) {
			mInstance = new CacheDB();
		}
		return mInstance;
	}
	
	public void insert(CacheTB entity) {
		mCacheTBDao.insert(entity);
	}
	
	public void insert(String key, String value) {
		CacheTB cacheTB = new CacheTB();
		cacheTB.setCkey(key);
		cacheTB.setCvalue(value);
		mCacheTBDao.insert(cacheTB);
	}

	public void insertInTx(List<CacheTB> entities) {
		mCacheTBDao.insertInTx(entities);
	}
	
	public void insertOrReplace(String key, String value) {
		CacheTB cacheTB = new CacheTB();
		cacheTB.setCkey(key);
		cacheTB.setCvalue(value);
		mCacheTBDao.insertOrReplace(cacheTB);
	}
	
	public void insertOrReplace(CacheTB entity) {
		mCacheTBDao.insertOrReplace(entity);
	}
	
	public void insertOrReplaceTx(List<CacheTB> entities) {
		mCacheTBDao.insertOrReplaceInTx(entities);
	}
	
	public void update(CacheTB entity) {
		mCacheTBDao.update(entity);
	}
	
	public void update(String key, String value) {
		CacheTB cacheTB = new CacheTB();
		cacheTB.setCkey(key);
		cacheTB.setCvalue(value);
		mCacheTBDao.update(cacheTB);
	}
	
	public void updateInTx(MemoryCache mMemeryCache) {
		List<CacheTB> mLst = mMemeryCache.memoryToCacheTB();
		mCacheTBDao.updateInTx(mLst);
	}
	
	public void updateInTx(List<CacheTB> entities) {
		mCacheTBDao.updateInTx(entities);
	}

	public void delete(CacheTB entity) {
		mCacheTBDao.delete(entity);
	}

	public void deleteInTx(List<CacheTB> entities) {
		mCacheTBDao.deleteInTx(entities);
	}
	
	public List<CacheTB> getCacheData() {
		QueryBuilder<CacheTB> query= mCacheTBDao.queryBuilder();
		return query.build().list();
	}
	
	public MemoryCache getLoadCache(){
		MemoryCache retTable = new MemoryCache();
		QueryBuilder<CacheTB> query = mCacheTBDao.queryBuilder();
		
		List<CacheTB> mLists = query.build().list();
		if(mLists != null && mLists.size() > 0){
			for(CacheTB list:mLists){
				retTable.put(list.getCkey(), list.getCvalue());
			}
		}
		return retTable;
	}
}
